import json

import requests
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from grafana_webhook.hmac import get_auth_header, get_url_path
from grafana_webhook.settings import TWEET_COLLECTOR_HOST


@csrf_exempt
def stop_tweet_collect(request):
    if request.method == 'POST':
        # 发起请求
        request_url = ''
        if request.GET['env'] == 'dev':
            request_url = 'http://%s/api/tweetsearch/pause?pause=true&threshold=20' % TWEET_COLLECTOR_HOST['dev']
        elif request.GET['env'] == 'qa':
            request_url = 'http://%s/api/tweetsearch/pause?pause=true&threshold=20' % TWEET_COLLECTOR_HOST['qa']
        elif request.GET['env'] == 'prod':
            request_url = 'http://%s/api/tweetsearch/pause?pause=true&threshold=20' % TWEET_COLLECTOR_HOST['prod']
        headers = request_func(request_url, 'POST')
        result = requests.post(url=request_url, headers=headers, timeout=120)
        if result.status_code == 200:
            return HttpResponse('已停止推文采集')
        return HttpResponse(status=500)


def request_func(request_url, method):
    auth_header = get_auth_header(method, get_url_path(request_url))
    headers = {
        "Connection": "close",
        "Date": auth_header['Date'],
        "Authorization": auth_header['Authorization']
    }
    return headers

